package com.example.service;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import cn.idev.excel.FastExcel;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.Constants;
import com.example.common.enums.ResultCodeEnum;
import com.example.common.enums.RoleEnum;
import com.example.entity.Account;
import com.example.entity.Staff;
import com.example.exception.CustomException;
import com.example.mapper.StaffMapper;
import com.example.utils.TokenUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 员工员业务处理
 **/
@Slf4j
@Service
public class StaffService extends ServiceImpl<StaffMapper, Staff> {

    @Resource
    private StaffMapper staffMapper;
    /**
     * 新增
     */
    public void add(Staff staff) {
        if (staffMapper.selectByUsername(staff.getUsername()) != null) {
            throw new CustomException(ResultCodeEnum.USER_EXIST_ERROR);
        }

        staff.setPassword(securePass(ObjectUtil.defaultIfNull(staff.getPassword(), Constants.USER_DEFAULT_PASSWORD)));
        staff.setName(ObjectUtil.defaultIfNull(staff.getName(), staff.getUsername()));
        staff.setWorkCode(ObjectUtil.defaultIfNull(staff.getWorkCode(), "STF" + IdUtil.getSnowflake().nextIdStr()));
        staff.setRole(ObjectUtil.defaultIfNull(staff.getRole(), RoleEnum.STAFF.name()));

        staffMapper.insert(staff);
    }

    /**
     * 删除
     */
    public void deleteById(Integer id) {
        staffMapper.deleteById(id);
    }

    /**
     * 批量删除
     */
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            staffMapper.deleteById(id);
        }
    }

    /**
     * 修改
     */
    public void updateByCheck(Staff staff) {
        if (staffMapper.selectById(staff.getId()) == null) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (staff.getPassword() != null) {
            staff.setPassword(securePass(staff.getPassword()));
        }
        staffMapper.updateById(staff);
    }

    /**
     * 根据ID查询
     */
    public Staff selectById(Integer id) {
        return staffMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<Staff> selectAll(Staff staff) {
        return staffMapper.selectAll(staff);
    }

    /**
     * 分页查询
     */
    public PageInfo<Staff> selectPage(Staff staff, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Staff> list = staffMapper.selectAll(staff);
        return PageInfo.of(list);
    }

    /**
     * 登录
     */
    public Staff login(Staff staff) {
        Staff dbStaff = staffMapper.selectByUsername(staff.getUsername());
        String input = securePass(staff.getPassword());
        String dbPwd = dbStaff.getPassword();
        log.info("input={} db={} staff.getPassword()={} eq={}", input, dbPwd,staff.getPassword() ,input.equals(dbPwd));
        if (ObjectUtil.isNull(dbStaff)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!securePass(staff.getPassword()).equals(dbStaff.getPassword())) {
            throw new CustomException(ResultCodeEnum.USER_ACCOUNT_ERROR);
        }
        // 生成token
        String tokenData = dbStaff.getId() + "-" + RoleEnum.STAFF.name();
        String token = TokenUtils.createToken(tokenData, dbStaff.getPassword());
        dbStaff.setToken(token);
        return dbStaff;
    }


    /**
     * 注册
     */
    public void register(Staff staff) {
        staff.setWorkCode(ObjectUtil.defaultIfNull(staff.getWorkCode(), "STF" + IdUtil.getSnowflake().nextIdStr()));
        staff.setRole(ObjectUtil.defaultIfNull(staff.getRole(), RoleEnum.STAFF.name()));
//        staff.setUsername(account.getUsername());
//        staff.setPassword(account.getPassword());
        this.add(staff);
    }
    /**
     * 修改密码
     */
    public void updatePassword(Account account) {
        Staff dbStaff = staffMapper.selectByUsername(account.getUsername());
        if (ObjectUtil.isNull(dbStaff)) {
            throw new CustomException(ResultCodeEnum.USER_NOT_EXIST_ERROR);
        }
        if (!account.getPassword().equals(dbStaff.getPassword())) {
            throw new CustomException(ResultCodeEnum.PARAM_PASSWORD_ERROR);
        }
        dbStaff.setPassword(account.getNewPassword());
        staffMapper.updateById(dbStaff);
    }

    private String securePass(String password) {
        return SecureUtil.md5(password + Constants.PASS_SALT);
    }

    public void exportDataByIds(HttpServletResponse response, List<Integer> ids) throws IOException {
        // 1. 查数据
        List<Staff> list = staffMapper.selectByIds(ids);

        // 2. 告诉浏览器这是文件
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("UTF-8");
        String fileName = URLEncoder.encode("员工数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-Disposition", "attachment;filename*=UTF-8''" + fileName + ".xlsx");

        // 3. 写 Excel
        FastExcel.write(response.getOutputStream(), Staff.class)
                .sheet("员工数据")
                .doWrite(list);
    }
}